package stattracker;

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.Method;

@SuppressWarnings("serial")
public class Halo3TeamFrame extends JFrame
{
	private Halo3Team team;
	private JPanel allGames, teamGames, teamStats;
	private JTabbedPane contentPane;
	public Halo3TeamFrame(Halo3Team data)
	{
		super(data.getName() + " Team Data");
		addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				dispose();
			}
		});
		setBackground(Color.BLACK);
		team = data;
		contentPane = new JTabbedPane();
		contentPane.setBackground(Color.BLACK);
		contentPane.setForeground(Color.WHITE);
		allGames = new JPanel(); teamGames = new JPanel();
		setGames();
		setStats();
		addTabs();
		setContentPane(contentPane);
		
		setPreferredSize(new Dimension(600, 600));
		
		pack();
		setLocation((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2-getSize().width/2, //Centers Width
				(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2-getSize().height/2); //Centers Height
		setVisible(true);
	}
	
	private void addTabs()
	{
		contentPane.addTab("All Games", MyUtils.makeScroll(allGames));
		contentPane.addTab("Team Games", MyUtils.makeScroll(teamGames));
		contentPane.addTab("Statistics", teamStats);
	}
	
	private void setGames()
	{
		allGames.setBackground(Color.BLACK);
		teamGames.setBackground(Color.BLACK);
		allGames.setLayout(new BoxLayout(allGames, BoxLayout.PAGE_AXIS));
		teamGames.setLayout(new BoxLayout(teamGames, BoxLayout.PAGE_AXIS));
		setAllGames();
		setTeamGames();
	}
	
	private void setAllGames()
	{
		Halo3TeamMember leader = team.getTeam().get(0);
		for(Halo3GameData g : leader.getAllGames())
		{
			allGames.add(formatGame(g.getID()));
			allGames.add(Box.createRigidArea(new Dimension(0, 2)));
		}
	}
	
	private void setTeamGames()
	{
		Halo3TeamMember leader = team.getTeam().get(0);
		for(Halo3GameData g : leader.getTeamGames())
		{
			teamGames.add(formatGame(g.getID()));
			teamGames.add(Box.createRigidArea(new Dimension(0, 2)));
		}
	}
	
	private JPanel formatGame(long gameID)
	{
		Halo3GameData base = team.getTeam().get(0).getGamesPlayed().get(gameID);
		JPanel game = new JPanel();
		game.setBackground(Color.BLACK);
		game.setLayout(new GridLayout(1, 4));
		game.add(gameLabel(base.getInfo().getGameType()));
		game.add(gameLabel(base.getInfo().getMap()));
		game.add(gameLabel(base.getInfo().getPlaylist()));
		game.add(urlButton(base.getInfo().getURL()));
		game.setBorder(BorderFactory.createLineBorder(Color.WHITE));
		return game;
	}
	
	private MyLabel gameLabel(String g)
	{
		MyLabel game = new MyLabel("  " + g);
		game.setBorder(BorderFactory.createMatteBorder(2, 1, 1, 1, Color.WHITE));
		return game;
	}
	
	private void setStats()
	{
		teamStats = new JPanel();
		teamStats.setBackground(Color.BLACK);
		teamStats.setLayout(new BorderLayout());
		JPanel header = new JPanel();
		header.setBackground(Color.BLACK);
		header.setLayout(new BoxLayout(header, BoxLayout.PAGE_AXIS));
		String teamHeader = team.getName() +":   ";
		for(Halo3TeamMember m : team.getTeam())
		{
			teamHeader += m.getName() + "     ";
		}
		MyLabel label = new MyLabel(teamHeader);
		label.setFont(new Font("Arial", Font.BOLD, 13));
		header.add(label);
		header.add(new MyLabel(String.format(" Team Games Played: %d    Win Ratio: %.3f", team.getTeamGamesPlayed(), team.winRatio())));
		/*
		JPanel games = new JPanel();
		games.setLayout(new BoxLayout(games, BoxLayout.PAGE_AXIS));
		Halo3TeamMember captain = team.getTeam().get(0);
		for(GameData g : captain.getTeamGames())
			games.add(urlButton(g.getInfo().getURL()));
		contentPane.add(MyUtils.makeScroll(games), BorderLayout.CENTER);
			*/
		JPanel players = new JPanel();
		players.setBackground(Color.BLACK);
		players.setLayout(new GridLayout(1, team.getTeam().size()));
		for(Halo3TeamMember m : team.getTeam())
			players.add(memberInfo(m));
		header.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.WHITE));
		teamStats.add(header, BorderLayout.PAGE_START);
		teamStats.add(players, BorderLayout.CENTER);
	}
	
	private JPanel memberInfo(Halo3TeamMember member)
	{
		JPanel info = new JPanel();
		info.setBackground(Color.BLACK);
		info.setLayout(new BoxLayout(info, BoxLayout.PAGE_AXIS));
		JLabel label = new MyLabel("    " + member.getName());
		label.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.WHITE));
		info.add(label);
		label = new MyLabel(" Kills: " + member.getTeamKills());
		info.add(label);
		label = new MyLabel(" Deaths: " + member.getTeamDeaths());
		info.add(label);
		label = new MyLabel(" Assists: " + member.getTeamAssists());
		info.add(label);
		
		info.setBorder(BorderFactory.createLineBorder(Color.WHITE));
		return info;
	}
	
	private JButton urlButton(String url)
	{
		final String web = url;
		JButton newButton = new JButton("Bungie.net");
		ImageIcon icon = createImageIcon("MedalIcons/bungieLogoSmall.jpg","");
		newButton = new JButton(icon);
		newButton.setMargin(new Insets(0,0,0,0));
		newButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				invokeBrowser(web);
			}
			//Should launch any web browser if available
			@SuppressWarnings("unchecked")
			public final boolean invokeBrowser(String url) 
			{
				String osName = System.getProperty("os.name");
				try {
					if (osName.startsWith("Mac OS")) 
					{
						Class fileMgr = Class.forName("com.apple.eio.FileManager");
						Method openURL = fileMgr.getDeclaredMethod("openURL",
								new Class[] {String.class});
						openURL.invoke(null, new Object[] {url});
					}
					else if (osName.startsWith("Windows"))
						Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
					else 
					{ //assume Unix or Linux
						String[] browsers = {
								"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
						String browser = null;
						for (int count = 0; count < browsers.length && browser == null; count++)
							if (Runtime.getRuntime().exec(
									new String[] {"which", browsers[count]}).waitFor() == 0)
								browser = browsers[count];
						if (browser == null)
							throw new Exception("Could not find web browser");
						else
							Runtime.getRuntime().exec(new String[] {browser, url});
					}
				}
				catch (Exception e) {
					String errMsg = "Failed to launch any web browser";
					JOptionPane.showMessageDialog(null, errMsg + ":\n" + e.getLocalizedMessage());
				}
				return true;
			}
		});
		return newButton;
	}
	
	protected static ImageIcon createImageIcon(String path, String description)
	{
		java.net.URL imgURL = Halo3Frame.class.getResource(path);
		if(imgURL != null) 
		{
			return new ImageIcon(imgURL, description);
		} 
		else
		{
			new ErrorMessage("Couldn't find file: " + path);
			System.err.println("Couldn't find file: " + path);
			return null;
		}
	}

}
